<!--
 * @Author: Liz.Zheng
 * @Date: 2021-11-24 09:35:16
 * @LastEditTime: 2023-02-15 11:22:20
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 
 * @Motto: Write the code. Change the world.
-->
<template>
  <div style="padding: 10px" class="owner-list">
    <div
      style="padding-bottom: 20px"
      class="owner-list-header"
      v-if="!isArchives"
    >
      <a-input-search
        :placeholder="ownerPlaceholder"
        style="width: 300px"
        allow-clear
        @search="onSearch"
      />
      <a-button @click="goArchivesList">归档业户列表</a-button>
    </div>
    <section class="header" v-if="isArchives">
      <a-page-header
        class="demo-page-header"
        style="border: 1px solid rgb(235, 237, 240)"
        @back="goBack(false)"
      >
        <template #title>
          <span>归档业户</span>
        </template>
        <template #backIcon>
          <ArrowLeftOutlined />
        </template>
        <template #extra>
          <a-input-search
            :placeholder="ownerPlaceholder"
            style="width: 200px"
            allow-clear
            @search="onSearch"
          />
        </template>
      </a-page-header>
    </section>
    <a-card style="margin-bottom: 20px" class="owner-card" v-if="!isArchives">
      <a-row>
        <a-col :span="6">
          <Statistic
            title="业户总数"
            :value="tenantsNumber"
            style="font-weight: 600"
          />
        </a-col>
        <a-col :span="6">
          <Statistic :value="companyTotal" style="font-weight: 600">
            <template #title>
              <span>企业总数</span>
            </template>
          </Statistic>
        </a-col>
        <a-col :span="6">
          <Statistic :value="personalTotal" style="font-weight: 600">
            <template #title>
              <span>个人总数</span>
            </template>
          </Statistic>
        </a-col>
        <a-col :span="6">
          <Statistic
            title="合同数量"
            :value="contractCount"
            style="font-weight: 600"
          />
        </a-col>
      </a-row>
    </a-card>

    <a-table
      :dataSource="dataSource"
      :columns="columns"
      :pagination="pagination"
      @change="handleTableChange"
      :scroll="{ x: 'max-content' }"
      rowKey="id"
      :customRow="customRow"
      :loading="loading"
      sticky
    >
      <template #title>
        <a-row type="flex" justify="space-between" align="middle">
          <a-col :flex="1">
            <a-tabs v-model:activeKey="ownerTypeTab" @change="handleTabChange">
              <a-tab-pane
                v-for="(item, index) of tabs"
                :key="item.key"
                :tab="item.tab"
              ></a-tab-pane>
            </a-tabs>
          </a-col>
          <a-col>
            <a-space>
              <custom-columns
                :colUrl="colUrl"
                :type="typeList"
                :resetType="resetType"
                from="ownerList"
                @getColumns="getColumns"
              />

              <a-dropdown v-if="!$store.getters.isMobile && !isArchives">
                <template #overlay>
                  <a-menu @click="handleMenuClick">
                    <a-menu-item v-if="canAddOwner" key="import"
                      >批量导入</a-menu-item
                    >
                    <a-menu-item key="export">表格导出</a-menu-item>
                  </a-menu>
                </template>
                <a-button>
                  更多
                  <DownOutlined />
                </a-button>
              </a-dropdown>

              <a-button
                type="primary"
                v-permission="['ownerList', 'curd', 'add']"
                @click="OwnerConEdit()"
                v-if="!isArchives"
              >
                <PlusOutlined />
                业户</a-button
              >
            </a-space>
          </a-col>
        </a-row>
      </template>

      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key === 'businessScope'">
          <a-tooltip>
            <template #title>
              {{ record.business_info.businessScope }}
            </template>
            {{ record.business_info.businessScope }}
          </a-tooltip>
        </template>
        <template v-if="column.key === 'tags'">
          <span>
            <TagList :list="record.tag_info_arr" :type="2" />
          </span>
        </template>
        <template v-if="column.key === 'type'">
          <span>{{ record.invoice_info.invoice_type_txt }}</span>
        </template>
        <template v-if="column.key === 'info_taxpayerIdNumber'">
          <span>{{ record.invoice_info.taxpayerIdNumber }}</span>
        </template>
        <template v-if="column.key === 'suggest_txt'">
          <span :class="record.is_suggest === 1 ? 'primary-color' : ''">{{
            record.suggest_txt
          }}</span>
        </template>
        <template v-if="column.key === 'bank'">
          <span>{{ record.invoice_info.bank }}</span>
        </template>
        <template v-if="column.key === 'account'">
          <span>{{ record.invoice_info.account }}</span>
        </template>
        <template v-if="column.key === 'info_address'">
          <span>{{ record.invoice_info.address }}</span>
        </template>
        <template v-if="column.key === 'action'">
          <a-button
            type="link"
            @click.stop="OwnerConEdit(record.id)"
            v-permission="['ownerList', 'curd', 'edit']"
            >编辑</a-button
          >
          <a-button
            type="link"
            danger
            v-permission="['ownerList', 'curd', 'delete']"
            @click.stop="OwnerConDelet(record.id)"
            >删除</a-button
          >
        </template>
      </template>
    </a-table>
    <OwnerContEdit
      :visible="visible"
      @cancel="handleBuildingClose"
      @updateList="updateList"
      :id="Ids"
      @btnok="searchClose"
    />
    <!-- 导入房源 -->
    <Import :visible="visibleImport" @refresh="refreshList" @clear="btnClear" />

    <!-- 表格导出 -->
    <ExportComponents
      v-if="isExport"
      :visible="isExport"
      :title="exportTitle"
      url="/owner/manage"
      service="/org"
      method="get"
      :params="paramses"
      :limit="500"
      :columnstitle="listHanders"
      :custom_result="customArray"
      :custom_data="true"
      @customDataFunc="customResult"
      @request="$utils.commonRequest"
      @cancel="changeExport"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  createVNode,
  watch,
  onActivated,
  reactive,
  toRefs,
} from "vue";
import {
  ArrowLeftOutlined,
  DownOutlined,
  PlusOutlined,
  UploadOutlined,
} from "@ant-design/icons-vue";
import { Statistic } from "ant-design-vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import OwnerContEdit from "./modules/OwnerContEdit.vue";
import Import from "./modules/Import.vue";
import { Modal, message } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import TagList from "../../../components/Tag/show.vue";
import store from "../../../store";
import { useRouter } from "vue-router";
import CustomColumns from "../../../components/CustomColumns/index.vue";
import BLCOMMON, { ExportComponents } from "bl-common-vue3";
const ownerFirstType = ["apartment", "village"];

export default defineComponent({
  name: "ownerList",
  components: {
    DownOutlined,
    ArrowLeftOutlined,
    Statistic,
    PlusOutlined,
    OwnerContEdit,
    TagList,
    UploadOutlined,
    Import,
    CustomColumns,
    ExportComponents,
  },
  props: {
    isArchives: {
      type: Boolean,
      default: false,
    },
  },
  setup(props) {
    const $router = useRouter();
    const canAddOwner = BLCOMMON.utils.getBtnPermission([
      "ownerList",
      "curd",
      "add",
    ]);
    // 租客列表
    const visible = ref(false);
    const Ids = ref();
    const OwnerConEdit = (villageId) => {
      Ids.value = villageId || 0;
      visible.value = true;
    };
    const villageType = store.getters.buildingInfo.villageType;

    const state = reactive({
      ownerTypeTab: "company",
      personalTotal: 0,
      companyTotal: 0,
      typeList: "user_owner_list_field1",
      resetType: "autoOwnerListColumn1",
      is_suggest: null,
      suggestArr: [],
      villageArr: [],
      villageFilter: [],
      tabs: [],
      ownerPlaceholder: `请搜索业户名称`,
      paramses: {},
      exportTitle: `业户列表导出`,
      listHanders: [],
      isExport: false,
      customArray: [],
    });

    const getOtherList = async (is_personal, tabType) => {
      let params = {
        page: 1,
        pageSize: 10,
        is_personal: is_personal,
      };
      if (props.isArchives) {
        params.is_archive = 1;
      } else {
        delete params.is_archive;
      }
      params.type = 0;
      state.paramses = { ...params };
      await request.get("/org", "/owner/manage", params).then((res) => {
        if (res.list.length > 0) {
          if (tabType === "company") {
            state.tabs.push({
              key: "company",
              tab: `企业列表`,
            });
          } else {
            state.tabs.push({
              key: "person",
              tab: `个人列表`,
            });
          }
        }
        state.ownerTypeTab = state.tabs[0].key;
        state.resetType =
          state.tabs[0].key === "company"
            ? "autoOwnerListColumn1"
            : "autoOwnerListColumn2";
        state.typeList =
          state.tabs[0].key === "company"
            ? "user_owner_list_field1"
            : "user_owner_list_field2";
      });
    };

    if (ownerFirstType.includes(villageType)) {
      // 小区特殊处理
      state.ownerTypeTab = "person";
      state.typeList = "user_owner_list_field2";
      state.resetType = "autoOwnerListColumn2";
    } else {
      state.ownerTypeTab = "company";
      state.typeList = "user_owner_list_field1";
      state.resetType = "autoOwnerListColumn1";
    }

    const getTabs = async () => {
      if (ownerFirstType.includes(villageType)) {
        // 小区 特殊处理
        state.tabs = [
          {
            key: "person",
            tab: `个人列表`,
          },
        ];
        await getOtherList(0, "company");
      } else {
        state.tabs = [
          {
            key: "company",
            tab: `企业列表`,
          },
        ];
        await getOtherList(1, "person");
      }
    };
    // 删除按钮
    const Modals = ref(false);
    const OwnerConDelet = (deletId) => {
      Modals.value = true;
      Modal.confirm({
        title: `确认删除该业户联系人么`,
        icon: createVNode(ExclamationCircleOutlined),
        okText: "确认",
        cancelText: "取消",
        onOk() {
          request.del("/org", "/owner/manage", { id: deletId }).then((res) => {
            page.value =
              dataSource.value.length == 1 ? page.value - 1 : page.value;
            init(true);
            message.success("删除成功");
          });
        },
      });
    };
    // 关闭弹窗
    const handleBuildingClose = () => {
      visible.value = false;
    };
    const Submit = () => {
      visible.value = false;
      getBuildingList();
    };

    // 自定义列表展示
    const colUrl = ref({
      server: "/org",
      url: "/org/ownerListColumn",
    });
    const loading = ref(false);
    const columns = ref([]);
    const sorterColumns = ["business_info_founding_time"];
    const ellipsisColums = ["businessScope"];
    const getColumns = (data) => {
      columns.value = [];
      let list = JSON.parse(JSON.stringify(data));
      list.forEach((item, index) => {
        if (item.key == "name") {
          item.title = `业户名称`;
        }
        let newItem = {
          title: BLCOMMON.utils.L(item.title),
          dataIndex: item.key,
          key: item.key,
          width: 200,
        };
        if (index == 0) {
          newItem.fixed = store.getters.isMobile ? undefined : "left";
        }
        if (ellipsisColums.includes(item.key)) {
          newItem.ellipsis = true;
        }
        if (sorterColumns.includes(item.key)) {
          newItem.sorter = true;
        }
        columns.value.push(newItem);
      });
      let actionItem = {
        title: "操作",
        key: "action",
        dataIndex: "action",
        width: 110,
        fixed: "right",
      };
      columns.value.push(actionItem);
      getListInit();
    };

    const handleTabChange = () => {
      page.value = 1;
      state.resetType =
        state.ownerTypeTab === "company"
          ? "autoOwnerListColumn1"
          : "autoOwnerListColumn2";
      state.typeList =
        state.ownerTypeTab === "company"
          ? "user_owner_list_field1"
          : "user_owner_list_field2";
      getBuildingList();
    };

    const dataSource = ref([]);

    // 分页
    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));
    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      limit.value = pager.pageSize;
      const suggestFilterList = filters?.suggest_txt;
      let is_suggest = null;
      if (suggestFilterList?.length) {
        if (suggestFilterList.length === 1) {
          is_suggest = suggestFilterList[0];
        } else {
          is_suggest = null;
        }
      } else {
        is_suggest = null;
      }
      state.is_suggest = is_suggest;
      state.villageFilter = filters?.village_name || [];
      getBuildingList(sorter.order);
    };

    const current = ref(6);
    const statisticData = ref({});
    const tenantsNumber = ref();
    const contractCount = ref();
    // 列表数据请求

    const getBuildingList = (createTimeAsc) => {
      loading.value = true;
      let params = {
        page: page.value,
        pageSize: limit.value,
        sort:
          createTimeAsc == "ascend"
            ? "createTimeAsc"
            : createTimeAsc == "descend"
            ? "createTimeDesc"
            : undefined,
        keywords: valueSearch.value,
        is_personal: state.ownerTypeTab === "person" ? 1 : 0,
        village_id: state.villageFilter.join(","),
      };
      if (
        (state.is_suggest === 0 || state.is_suggest === 1) &&
        state.ownerTypeTab === "company"
      ) {
        params.is_suggest = state.is_suggest;
      }
      if (props.isArchives) {
        params.is_archive = 1;
      } else {
        delete params.is_archive;
      }
      params.type = 0;
      state.paramses = { ...params };
      request.get("/org", "/owner/manage", params).then((res) => {
        dataSource.value = res.list.map((item) => {
          return {
            ...item,
            ...item.business_info,
          };
        });

        tenantsNumber.value = res.personalTotal + res.companyTotal;
        total.value = res.total;
        contractCount.value = res.contractCount;
        state.personalTotal = res.personalTotal;
        state.companyTotal = res.companyTotal;
        loading.value = false;
      });
    };
    // getBuildingList();
    const updateList = () => {
      handleBuildingClose();
      init();
    };
    // 自定义列表
    const drawerChange = ref(false);
    const customizationList = () => {
      drawerChange.value = true;
    };
    //搜索
    const valueSearch = ref("");
    const onSearch = (searchValue) => {
      valueSearch.value = searchValue;
      page.value = 1;
      getBuildingList(undefined);
    };
    const searchClose = () => {
      visible.value = false;
      init(true);
    };

    // 导入房源
    const visibleImport = ref(false);
    const btnImport = () => {
      visibleImport.value = true;
    };
    const btnClear = () => {
      visibleImport.value = false;
    };
    const refreshList = () => {
      init();
    };

    // 自定义行
    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => handleTableRowClick(record),
      };
    };
    // 点击行
    const handleTableRowClick = (record) => {
      console.log("handleTableRowClick", record);
      if (window.__MICRO_APP_ENVIRONMENT__) {
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `org_ownerDetail_${record.id}`,
            app: 'org',
            name: `客商详情【${record.name}】`,
            url: `/village/ownerDetail?id=${record.id}&noBack=1`,
          }
        })
      } else {
        $router.push({ name: "ownerDetail", query: { id: record.id } });
      }
    };

    const getListInit = () => {
      request.get("/org", "/owner/listInit").then((res) => {
        const { initData } = res;
        state.suggestArr = (initData?.suggestArr || []).map((item) => {
          return {
            value: item.key,
            text: item.name,
          };
        });
        state.villageArr = (initData?.villageArr || []).map((item) => {
          return {
            value: item.key,
            text: item.name,
          };
        });
        columns.value.forEach((item, index) => {
          if (item.dataIndex === "suggest_txt") {
            item.filters = state.suggestArr;
          }
          if (item.dataIndex === "village_name") {
            item.filters = state.villageArr;
          }
        });
      });
    };

    const goArchivesList = () => {
      $router.push({ name: "OwnerArchives" });
    };

    const goBack = () => {
      $router.back();
    };

    // 导出报表
    const downLoadClick = () => {
      let handerData = utils.deepClone(columns.value);
      state.listHanders = handerData.reduce((obj, v) => {
        obj[v.key] = v.title;
        if (v.key == "action") {
          obj[v.key] = undefined;
          v.key = undefined;
        }
        return obj;
      }, {});
      state.isExport = true;
    };

    const customResult = (list) => {
      list.forEach((item) => {
        item.tag_info_arr = item.tag_info_arr || [];
        (item.tags = item.tag_info_arr.map((tag) => tag.name).join("，") || ""),
          (item.bank = item?.invoice_info?.bank),
          (item.account = item?.invoice_info?.account),
          (item.info_taxpayerIdNumber = item?.invoice_info?.taxpayerIdNumber),
          (item.address = item?.business_info?.address),
          (item.organizationCode = item?.business_info?.organizationCode),
          (item.district = item?.business_info?.district),
          (item.industry = item?.business_info?.industry),
          (item.companyType = item?.business_info?.companyType);
      });
      state.customArray = list;
    };

    const changeExport = () => {
      state.isExport = false;
      message.success("导出成功,请等待文件生成");
    };

    const handleMenuClick = ({ key }) => {
      if (key === "import") {
        // 导入
        btnImport();
      }
      if (key === "export") {
        // 导出
        downLoadClick();
      }
    };

    const init = async (type) => {
      if (!type) {
        await getTabs();
      }
      getBuildingList();
    };

    if (props.isArchives) {
      init();
    }
    onActivated(() => {
      init();
    });

    return {
      Submit,
      searchClose,
      columns,
      dataSource,
      statisticData,
      current,
      visible,
      pagination,
      OwnerConEdit,
      handleBuildingClose,
      tenantsNumber,
      updateList,
      Ids,
      OwnerConDelet,
      drawerChange,
      customizationList,
      onSearch,
      contractCount,
      handleTableChange,
      btnImport,
      visibleImport,
      btnClear,
      refreshList,
      customRow,
      colUrl,
      getColumns,
      loading,
      ...toRefs(state),
      handleTabChange,
      goArchivesList,
      goBack,
      handleMenuClick,
      canAddOwner,
      changeExport,
      customResult,
    };
  },
});
</script>

<style lang="less" scoped>
.owner-list {
  .header {
    background-color: #ffffff;
    margin-bottom: 10px;

    :deep(.tag-list .tag) {
      margin-right: 10px;
    }

    :deep(.ant-tabs-bar) {
      margin-bottom: 0;
      border-bottom: none;
    }

    :deep(.ant-tabs-ink-bar) {
      height: 3px;
    }
  }
  :deep(.ant-statistic) {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .owner-card {
    .ant-col {
      &:not(:last-child) {
        border-right: 1px solid rgba(0, 0, 0, 0.06);
      }
    }
  }
}

:deep(.ant-btn-link) {
  margin-right: 0;
}
:deep(.ant-table-title) {
  padding: 10px;
}
:deep(.ant-tabs-bar) {
  border-bottom: none;
}
.primary-color {
  color: @primary-color;
}
.owner-list-header {
  display: flex;
  justify-content: space-between;
}
</style>
